import {
  ui
} from "./ui"

export const pay = {
  async qrPay(data, cb) {
    this.loading()
    const paymentRes = await wx.cloud.callFunction({
      name: 'qrGetPayment',
      data
    })

    if (paymentRes.result.returnCode != 'SUCCESS') {
      this.throwError(paymentRes)
    }

    // call wx.requestPayment
    this.wxPay(paymentRes.result.payment).then(res => {
      this.loading(false)
      cb && cb(res)
    })
  },
  async payOrder(data, cb) { // fee: yuan
    const {
      id, // order id, 支付已有订单只需传入id即可
      title,
      remark,
      goodsList,
      stepFee,
      vipPrice,
      fee,
      ticketInfo, // 水票订单
      couponInfo,
      deductFeeInfo,
    } = data
    const body = title
    const totalFee = Math.round(fee * 100) // fen

    // 1. 获取payment对象（创建order）
    this.loading()
    const payMentRes = await this.getPayMent({
      id,
      totalFee,
      body,
      remark,
      goodsList,
      stepFee,
      vipPrice,
      ticketInfo,
      couponInfo,
      deductFeeInfo
    })

    if (payMentRes.result.returnCode != 'SUCCESS') {
      ui.toast(false)
      this.throwError(payMentRes)
    }

    // 2. 调用小程序支付（payCallBack被调用）
    const payRes = await this.wxPay(payMentRes.result.payment) // wx.requestPayment
    this.loading(false)

    // 3. 处理支付结果
    if (cb) cb(payRes);
  },
  wxPay(payment) {
    return new Promise((resolve, rejects) => {
      wx.requestPayment({
        ...payment,
        success(res) {
          resolve({
            status: 'success',
            res: res
          })
        },
        fail(err) {
          resolve({
            status: 'fail',
            res: err
          })
        }
      })
    })
  },
  getPayMent(data) {
    return new Promise((resolve, rejects) => {
      wx.cloud.callFunction({
        name: 'getPayment',
        data,
        success(res) {
          resolve(res)
        },
        fail(err) {
          resolve(err)
        }
      })
    })
  },
  async refound(data, cb) {
    const {
      totalFee,
      refoundFee,
      outTradeNo,
      title
    } = data
    const modal = await wx.showModal({
      title: '提示',
      content: '确定发起退款吗？',
      confirmText: '退款',
    });
    if (!modal.confirm) return
    ui.loading()
    console.log({
      nonce_str: this.genUuid(32, 16), // 可以参考uuid()生成算法生成本字段
      out_trade_no: outTradeNo, // 支付时生成的
      total_fee: Math.round(totalFee * 100),
      refund_fee: Math.round(refoundFee * 100),
      title
    })
    wx.cloud.callFunction({
      //调用cloudRefund云函数进行退款
      name: 'refound',
      data: {
        nonce_str: this.genUuid(32, 16), // 可以参考uuid()生成算法生成本字段
        out_trade_no: outTradeNo, // 支付时生成的
        total_fee: Math.round(totalFee * 100),
        refund_fee: Math.round(refoundFee * 100),
        title
      }
    }).then((res) => {
      ui.loading(false)
      const returnCode = res.result?.returnCode
      const success = (returnCode == 'SUCCESS')
      if (cb) cb(success, res)
      ui.toast(success, success ? '' : res.result.returnMsg)
    }).catch((err) => {
      console.error(err);
      ui.loading(false)
      ui.toast(false, '退款出错，请稍后再试')
    })
  },
  genUuid(len, radix) { // 指定长度和基数
    var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
    var uuid = [],
      i;
    radix = radix || chars.length;

    if (len) {
      // Compact form
      for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
    } else {
      // rfc4122, version 4 form
      var r;

      // rfc4122 requires these characters
      uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
      uuid[14] = '4';

      // Fill in random data.  At i==19 set the high bits of clock sequence as
      // per rfc4122, sec. 4.1.5
      for (i = 0; i < 36; i++) {
        if (!uuid[i]) {
          r = 0 | Math.random() * 16;
          uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
        }
      }
    }

    return uuid.join('');
  },
  loading(load) {
    if (load !== false) {
      wx.showLoading({
        title: '微信支付',
        mask: true
      })
    } else {
      wx.hideLoading({
        success: (res) => {},
      })
    }
  },
  throwError(msg) {
    ui.loading(false)
    throw msg
  }
}